package cn.sstir.api.common.util;

import cn.sstir.fastspringboot.core.util.MD5Util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static cn.sstir.api.common.constants.ClientConstants.CLIENT_SECRET;

/**
 * @title: ApiSignatureUtil
 * @description: Api签名工具类
 * @author: fli
 * @email: fli@sstir.cn
 * @date: 2019/8/23 11:05
 */
public class ApiSignatureUtil {

    /**
     * 生成签名sn
     *
     * @param params       url参数
     * @param clientSecret 应用的密钥,不在url中传输
     * @return
     */
    public static String generateSign(Map<String, Object> params, String clientSecret) {
        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuilder temp = new StringBuilder();
        boolean first = true;
        for (Object key : keys) {
            if (CLIENT_SECRET.equals(key)) continue;
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            temp.append(valueString);
        }
        temp.append("&").append(CLIENT_SECRET).append("=").append(clientSecret);
        return MD5Util.encrypt(temp.toString(), 2).toUpperCase();
    }


    public static void main(String[] args) {
        long time = System.currentTimeMillis() / 1000;
        System.out.println(time);
        Map<String, Object> map = new HashMap<>();
        map.put("client_id", "zhiku");
        map.put("timestamp", time);
        String sn = generateSign(map, "d5bc65391a5672c2f31617cc734bb0d3");
        System.out.println(sn);
    }

}
